package com.example.admin.smstest.sms;

import android.app.Activity;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import com.example.admin.smstest.ConnectionManager;
import com.example.admin.smstest.utils.ByteUtil;
import com.example.admin.smstest.utils.CrcOperateUtil;
import com.example.admin.smstest.utils.DataUtil;
import com.example.admin.smstest.utils.DateUtil;
import com.example.admin.smstest.utils.SharedPreferencesUtils;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import static com.example.admin.smstest.utils.ByteUtil.hexStringToBytes;

/**
 * 获取短信内容，并发送
 * Created by admin on 2017/6/9.
 */

public class SmsObserver extends ContentObserver {

    private Context mContext;
    private static final String TAG = SmsObserver.class.getSimpleName();
    private static final String MARKER = "YOUR_KEYWORD";
    private ConnectionManager mConnectionManager;//链接监听类
    private Cursor cursor = null;
    private int first = 0;
    private int second = 0;
    private String smsIdFirst;
    private String smsIdSecond;

    public SmsObserver(Context context, Handler handler) {
        super(handler);
        this.mContext = context;
        SharedPreferencesUtils sp = SharedPreferencesUtils.getInstance(context,"sms_data");
        String address = sp.get("device_address","").toString();
        mConnectionManager.connect(address);
        mConnectionManager = new ConnectionManager(mConnectionListener);
        mConnectionManager.startListen();

    }

    public void onChange (boolean selfChange) {
        super.onChange(selfChange);
        onChange(selfChange, null);
    }

    @Override
    public void onChange(boolean selfChange, Uri uri) {
        getSendSms(uri);
        getReceiveSms(uri);
    }

    private void getReceiveSms(Uri uri) {
        if (uri == null) {
            uri = Uri.parse("content://sms/inbox");
        }
        if (uri.toString().equals("content://sms/raw")) {
            return;
        }
        try {
            cursor = mContext.getContentResolver().query(
                    Uri.parse("content://sms/inbox"), null, null,
                    null,
                    "date desc");
            if(cursor!=null){
                if(cursor.moveToNext()){//不遍历只拿当前最新的一条短信 moveToFirst() moveToNext()
                    String smsId = cursor.getString(cursor.getColumnIndex("_id"));
                    if (!smsId.equals(smsIdFirst)){
                        if (first == 0){
                            smsIdFirst = smsId;
                            first++;
                        }else{
                            System.out.println("smsId inbox=="+smsId);
                            smsIdFirst = smsId;
                            String date = DateUtil.getTime(System.currentTimeMillis());//时间
                            String type = cursor.getString(cursor.getColumnIndex("type"));;//状态 1==接受短信 2==发送短信
                            String id = cursor.getString(cursor.getColumnIndex("thread_id"));//id 短信Id
                            String address = cursor.getString(cursor.getColumnIndex("address"));// 短信号码
                            String body = cursor.getString(cursor.getColumnIndex("body"));
                            cursor.close();
                            first++;
                            System.out.println("type=="+type);
                            System.out.println(body);
                            // 已经有了sms 做任何你想做的事情
                            sendMessage(date,id,address,body,type);
                        }
                    }
                }
            }else{
                Log.e(TAG, "error: cursor == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(cursor!=null){cursor.close();}
        }
    }

    private void getSendSms(Uri uri){
        if (uri == null) {
            uri = Uri.parse("content://sms/sent");
        }
        if (uri.toString().equals("content://sms/raw")) {
            return;
        }
        try {
            cursor = mContext.getContentResolver().query(
                    Uri.parse("content://sms/sent"), null, null,
                    null,
                    "date desc");
            if(cursor!=null){
                if(cursor.moveToFirst()){//不遍历只拿当前最新的一条短信 moveToFirst() moveToNext()
                    String smsId = cursor.getString(cursor.getColumnIndex("_id"));
                    if (!smsId.equals(smsIdSecond)){
                        if (second == 0){
                            smsIdSecond = smsId;
                            second++;
                        }else{
                            System.out.println("smsId sent=="+smsId);
                            smsIdSecond = smsId;
                            String date = DateUtil.getTime(System.currentTimeMillis());//时间
                            String type = cursor.getString(cursor.getColumnIndex("type"));;//状态 1==接受短信 2==发送短信
                            String id = cursor.getString(cursor.getColumnIndex("thread_id"));//id 短信Id
                            String address = cursor.getString(cursor.getColumnIndex("address"));// 短信号码
                            String body = cursor.getString(cursor.getColumnIndex("body"));
                            cursor.close();
                            System.out.println("type=="+type);
                            System.out.println(body);
                            // 已经有了sms 做任何你想做的事情
                            second++;
                            sendMessage(date,id,address,body,type);
                        }
                    }
                }
            }else{
                Log.e(TAG, "error: cursor == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(cursor!=null){cursor.close();}
        }
    }

    /**
     * 链接监听
     */
    private ConnectionManager.ConnectionListener mConnectionListener = new ConnectionManager.ConnectionListener() {

        @Override
        public void onConnectStateChange(int oldState, int State) {
        }

        @Override
        public void onListenStateChange(int oldState, int State) {
        }

        @Override
        public void onSendData(boolean suc, byte[] data) throws UnsupportedEncodingException {
            System.out.println("发送监听："+ Arrays.toString(data));
            //getData(data);
        }

        @Override
        public void onReadData(byte[] data) {
            //System.out.println("接收："+Arrays.toString(data));
            //getData(data);
        }
    };

    /**
     * 发送短信数据
     * @param date
     * @param id
     * @param numbers
     * @param body
     * @throws UnsupportedEncodingException
     */
    private void sendMessage(String date,String id,String numbers,String body,String type) throws UnsupportedEncodingException{
        // 1.帧头
        byte[] frameHeader = DataUtil.MAGICTYPES;
        // 2.作用域
        byte[] function = DataUtil.FUNCTION;
        //                   序列号|业务号|操作类型 (type)| Type(TLV)
        byte[] baowentou = {  0x01,  0x05,        0x03,        0x01};// 10B

        // value的长度
        // a.时间
        byte[] timeB = hexStringToBytes(date);
        // b.destination  1==接受 2==发送
        byte[] destinationB = ByteUtil.intToHexBytes(Integer.parseInt(type));
        // c.Short message ID number
        int idI = Integer.parseInt(id,10);
        byte[] idB = ByteUtil.intToHexBytes(idI);
        // d.number 短信的电话号码
        byte[] numberB = ByteUtil.getByte(numbers);
        // e.获取当前的短信内容

        byte[] smsValueB = null;
        if (body.length() <= 100){
            byte[] totalB = {0x01,0x00};
            byte[] totalC = {0x01,0x00};
            byte[] bodyByte= ByteUtil.getByte(body);
            // TLV中的Value
            smsValueB = ByteUtil.concatAll(timeB,destinationB,idB,numberB,bodyByte);
            // 3.短信长度
            byte[] smsByteLength = ByteUtil.intToHexBytes(smsValueB.length);
            // 4.TLV长度
            byte[] valueTotalLength = ByteUtil.intToHexBytes(smsValueB.length+7);
            // 加crc校验
            byte[] andData = ByteUtil
                    .concatAll(function,valueTotalLength ,totalB,totalC,baowentou,smsByteLength,smsValueB);
            byte[] endData = CrcOperateUtil.setParamCRC(andData);
            byte[] data = ByteUtil.concatAll(frameHeader, endData);
            mConnectionManager.sendData(data);
            System.out.println(Arrays.toString(data));
            boolean sendSuccess = mConnectionManager.sendData(data);
            System.out.println("发送成功？"+sendSuccess);
        }else{
            int total = body.length()/100 + 1;
            //总包数totalB为真实值
            byte[] totalB = ByteUtil.getPackets(total);
            for(int i = 0;i < total ;i++){
                System.out.println("一共几个包"+total);
                if(i != total -1){
                    //当前报数
                    byte[] totalC = ByteUtil.getPackets(i+1);
                    String body1 = body.substring(i*100,(i+1)*100);
                    byte[] bodyByte= ByteUtil.getByte(body1);
                    // TLV中的Value
                    smsValueB = ByteUtil.concatAll(timeB,destinationB,idB,numberB,bodyByte);
                    // 3.短信长度
                    byte[] smsByteLength = ByteUtil.intToHexBytes(smsValueB.length);
                    // 4.TLV长度
                    byte[] valueTotalLength = ByteUtil.intToHexBytes(smsValueB.length+7);
                    // 加crc校验
                    byte[] andData = ByteUtil
                            .concatAll(function,valueTotalLength ,totalB,totalC,baowentou,smsByteLength,smsValueB);
                    byte[] endData = CrcOperateUtil.setParamCRC(andData);

                    byte[] data = ByteUtil.concatAll(frameHeader, endData);
                    System.out.println("长度=="+data.length);
                    System.out.println(Arrays.toString(data));
                    boolean sendSuccess = mConnectionManager.sendData(data);
                    System.out.println("发送成功？"+sendSuccess);
                }else if(i == (total - 1)){
                    //当前报数，最后一个包名
                    byte[] totalC = ByteUtil.getPackets(i+1);
                    String body1 = body.substring(i*100,body.length());
                    byte[] bodyByte= ByteUtil.getByte(body1);
                    // TLV中的Value
                    smsValueB = ByteUtil.concatAll(timeB,destinationB,idB,numberB,bodyByte);
                    // 3.短信长度
                    byte[] smsByteLength = ByteUtil.intToHexBytes(smsValueB.length);
                    // 4.TLV长度
                    byte[] valueTotalLength = ByteUtil.intToHexBytes(smsValueB.length+7);
                    // 加crc校验
                    byte[] andData = ByteUtil
                            .concatAll(function,valueTotalLength ,totalB,totalC,baowentou,smsByteLength,smsValueB);
                    byte[] endData = CrcOperateUtil.setParamCRC(andData);
                    byte[] data = ByteUtil.concatAll(frameHeader, endData);
                    mConnectionManager.sendData(data);
                }
            }
        }

        //System.out.println("发送"+Arrays.toString(data));
        // boolean sendSuccess = mConnectionManager.sendData(data);
        // System.out.println("发送成功？"+sendSuccess);
        // }
        //}
    }

    /**
     * 注册一个更改sms的监视器
     */
    public void register() {
        Log.d(TAG, "Register sms monitor");
        mContext.getContentResolver().registerContentObserver(
                Uri.parse("content://sms/"), true, this);
    }

    /**
     * 取消对sms更改的监视器
     */
    public void unRegister() {
        Log.d(TAG, "Unregister sms monitor");
        mContext.getContentResolver().unregisterContentObserver(this);
    }
}

//
//sms主要结构：
//        　　_id：短信序号，如100
//        　　thread_id：对话的序号，如100，与同一个手机号互发的短信，其序号是相同的
//        　　address：发件人地址，即手机号，如+86138138000
//        　　person：发件人，如果发件人在通讯录中则为具体姓名，陌生人为null
//        　　date：日期，long型，如1346988516，可以对日期显示格式进行设置
//        　　protocol：协议0SMS_RPOTO短信，1MMS_PROTO彩信
//        　　read：是否阅读0未读，1已读
//        　　status：短信状态-1接收，0complete,64pending,128failed
//        　　type：短信类型1是接收到的，2是已发出
//        　　body：短信具体内容
//        　　service_center：短信服务中心号码编号，如+8613800755500